#include "result.h"
#include "stdlib.h"

result_t* create_result(char* url, char* context, int count, time_t& check_time)
{
	result_t* result = new result_t;
	result->url = url;
	result->context = context;
	result->count = count;
	result->check_time = check_time;
	return result;
}

void release_result(result_t* result)
{
	assert(result != NULL);
	delete result;
}


result_union_t* create_result_union(const string& word)
{
	result_union_t* result_union = new result_union_t;
	result_union->word = word;
	return result_union;
}

void release_result_union(result_union_t* result_union)
{
	if(result_union == NULL) return;
	list<result_t*>::iterator it = result_union->results.begin();
	for(; it != result_union->results.end(); it++)
	{
		release_result(*it);
	}
	result_union->results.clear();
	delete result_union;
}

int add_result(result_union_t* result_union, result_t* result)
{
	assert(result_union != NULL && result != NULL);
	result_union->results.push_back(result);
	return 0;
}

void show_result(int fd, const string& word, result_union_t* result_union)
{
	string show, tmp;
	char count[16] = {0};
	tmp = "query word:";
	write(fd, tmp.c_str(), tmp.length());
	write(fd, word.c_str(), word.length());
	write(fd, "\n", sizeof("\n"));
	if(result_union == 0 || result_union->results.size() == 0)
	{
		tmp = "not found:-(";
		write(fd, tmp.c_str(), tmp.length());
		write(fd, "\n", sizeof("\n"));
		return ;
	}
	
	list<result_t*>::iterator it = result_union->results.begin();
	for(; it != result_union->results.end(); it++)
	{
		result_t* result = (*it);
		write(fd,"url:", strlen("url:"));
		write(fd, result->url.c_str(), result->url.length());
		write(fd, "\n", sizeof("\n"));
		if( result->context.length() > 0)
		{
			write(fd, result->context.c_str(), result->context.length());
			write(fd, "\n", sizeof("\n"));
		}
		
		sprintf(count, "%d", result->count);
		tmp = count;
		write(fd, "count:", strlen("count:"));
		write(fd, tmp.c_str(), tmp.length());
		write(fd, "\ttime:", sizeof("\ttime"));
		tmp = ctime(&result->check_time);
		write(fd, tmp.c_str(), tmp.length());
		write(fd, "\n", sizeof("\n"));
	}
}
